package utils

import (
	"net"
	"strings"

	"github.com/gin-gonic/gin"
)

// GetClientIP 获取客户端 IP 地址
func GetClientIP(c *gin.Context) string {
	// 优先从 X-Forwarded-For 获取
	clientIP := c.Request.Header.Get("X-Forwarded-For")
	if clientIP != "" {
		ips := strings.Split(clientIP, ",")
		if len(ips) > 0 {
			return strings.TrimSpace(ips[0])
		}
	}

	// 从 X-Real-IP 获取
	clientIP = c.Request.Header.Get("X-Real-IP")
	if clientIP != "" {
		return clientIP
	}

	// 从 RemoteAddr 获取
	ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
	if err != nil {
		return ""
	}

	return ip
}

// IsValidIP 验证 IP 地址是否合法
func IsValidIP(ip string) bool {
	return net.ParseIP(ip) != nil
}
